// Connection and traffic logger

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionLog {
    pub user_id: String,
    pub remote_addr: String,
    pub action: String,
    pub timestamp: DateTime<Utc>,
}

pub struct Logger {
    logs: Arc<RwLock<Vec<ConnectionLog>>>,
    max_logs: usize,
}

impl Logger {
    pub fn new(max_logs: usize) -> Self {
        Self {
            logs: Arc::new(RwLock::new(Vec::new())),
            max_logs,
        }
    }

    pub async fn log_connection(&self, user_id: String, remote_addr: String, action: String) {
        let log = ConnectionLog {
            user_id,
            remote_addr,
            action,
            timestamp: Utc::now(),
        };

        let mut logs = self.logs.write().await;
        logs.push(log);

        // Keep only recent logs
        if logs.len() > self.max_logs {
            logs.drain(0..logs.len() - self.max_logs);
        }
    }

    pub async fn get_logs(&self, limit: usize) -> Vec<ConnectionLog> {
        let logs = self.logs.read().await;
        logs.iter()
            .rev()
            .take(limit)
            .cloned()
            .collect()
    }

    pub async fn clear_logs(&self) {
        self.logs.write().await.clear();
    }
}

impl Default for Logger {
    fn default() -> Self {
        Self::new(10000)
    }
}
